<template>
  <div class="app-container">
    <el-form
      ref="listFilterRef"
      :model="list.filter"
      inline
      class="list-filter"
    >
      <el-form-item prop="name">
        <el-input
          v-model="list.filter.name"
          placeholder="请输入优惠码名称"
        ></el-input>
      </el-form-item>
      <el-form-item prop="code">
        <el-input
          v-model="list.filter.code"
          placeholder="请输入活动编码"
        ></el-input>
      </el-form-item>
      <el-form-item prop="frontStatus">
        <KiSelect
          v-model="list.filter.frontStatus"
          placeholder="请选择活动状态"
          :options="frontStatusList"
        />
      </el-form-item>
      <el-form-item prop="createUserName">
        <el-input
          v-model="list.filter.createUserName"
          placeholder="创建人"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="table-operation">
      <AuthButton @click="c" name="新增" />
      <el-pagination
        v-bind="elPaginationProps"
        :total="list.total"
        :currentPage.sync="list.filter.pageNo"
        :pageSize.sync="list.filter.pageSize"
      />
    </div>

    <el-table v-loading="list.loading" :data="list.data" v-bind="tableProp">
      <el-table-column label="活动ID" prop="id" />
      <el-table-column label="活动编码" prop="code" />
      <el-table-column label="优惠码名称" prop="name" />
      <el-table-column label="优惠内容" prop="preferenceType">
        <template slot-scope="{ row }">
          <template v-if="row.preferenceType">单商品免单</template>
          <template v-else>
            <template v-if="row.purchaseAbove">
              订单满{{ row.purchaseAbove | $cent2yuan }}元
            </template>
            <template v-else>无门槛</template>
            减免 {{ row.preferenceNum | $cent2yuan }}元
          </template>
        </template>
      </el-table-column>
      <el-table-column label="活动状态" prop="status">
        <template slot-scope="{ row }">
          {{ showDelete(row) | $value2label(frontStatusList) }}
        </template>
      </el-table-column>
      <el-table-column label="发放数量" prop="num" />
      <el-table-column label="已领取" prop="distributeNum" />
      <el-table-column label="已使用" prop="useNum" />
      <el-table-column label="创建人" prop="createUserName" />
      <el-table-column label="生成状态" prop="status">
        <template slot-scope="{ row }">
          <template v-if="row.status == 1">已生成</template>
          <template v-else-if="row.status == 0">生成中</template>
          <template v-else>已失效</template>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="320">
        <template slot-scope="{ row }">
          <AuthButton @click="r({ id: row.id })" name="查看" />
          <AuthButton
            v-if="showDelete(row) == 0 || showDelete(row) == 1"
            name="编辑"
            @click="u(row)"
          ></AuthButton>
          <AuthButton name="优惠码列表" @click="$refs.codeL.show(row)" />
          <AuthButton
            v-if="showDelete(row) == 0 || showDelete(row) == 1"
            name="优惠码推广"
            @click="createQrCode(row)"
          />
          <AuthButton
            v-if="showDelete(row) == 0 || showDelete(row) == 1"
            name="失效"
            @click="lose(row)"
          />
          <AuthButton
            v-if="showDelete(row) == 3 || showDelete(row) == 2"
            @click="d({ id: row.id })"
            name="删除"
          />
        </template>
      </el-table-column>
    </el-table>

    <KiFormDialog
      :show.sync="form.show"
      :title="formTitle"
      v-model="form.data"
      :submit="submitForm"
      :readonly="form.status === 'r'"
      ref="formRef"
      :loading="form.loading"
      width="1200px"
    >
      <template #el-form>
        <h2 class="title mt-0px">基本信息</h2>
        <el-form-item
          label="优惠码名称"
          prop="name"
          :verify="{ maxLength: 10 }"
        >
          <el-input
            v-model="form.data.name"
            placeholder="请输入优惠码活动名称"
          />
        </el-form-item>
        <el-form-item
          label="活动编码"
          prop="code"
          :verify="{ required: false, maxLength: 8 }"
        >
          <el-input v-model="form.data.code" placeholder="请输入活动编码" />
          <form-item-tip
            value="活动编码应用于渠道端快捷绑定多个优惠码活动，请确保活动编码的准确性"
          />
        </el-form-item>
        <el-form-item
          label="备注说明"
          prop="remark"
          :verify="{ required: false, maxLength: 15 }"
        >
          <el-input
            v-model="form.data.remark"
            placeholder="仅用作标记，不对外展示"
            :disabled="form.status !== 'c'"
          />
        </el-form-item>
        <el-form-item
          label="发放总量"
          prop="num"
          :verify="{ type: 'int', gt: 0, lte: 2000 }"
        >
          <el-input
            v-model="form.data.num"
            placeholder="单次添加请勿超过20000个"
            :disabled="form.status !== 'c'"
          />
          <form-item-tip
            value="创建后只能在优惠券列表-发放总量中添加数量，且数量不可减少，请谨慎设置"
          />
        </el-form-item>
        <el-form-item
          label="适用商品"
          prop="couponActivityProductCreateDtoList"
          verify
        >
          <BoundGoods
            v-if="form.show"
            dataKey="productId"
            v-model="form.data.couponActivityProductCreateDtoList"
            :disabled="form.status !== 'c'"
          />
        </el-form-item>
        <el-form-item label="优惠内容" prop="preferenceType" verify>
          <KiSelect
            v-model="form.data.preferenceType"
            placeholder="请选择优惠内容"
            :options="[
              { dataName: '减免', dataValue: 0 },
              { dataName: '单商品免单', dataValue: 1 }
            ]"
            :disabled="form.status !== 'c'"
          />
          <form-item-tip
            value="用户使用单商品免单优惠券时，可支持抵扣数量为1的订单金额"
          />
        </el-form-item>
        <el-form-item
          v-if="form.data.preferenceType === 0"
          label="减免金额"
          prop="preferenceNum"
          :verify="{ type: 'int', gt: 0 }"
        >
          <PriceInput
            v-model="form.data.preferenceNum"
            :disabled="form.status !== 'c'"
            placeholder="请输入减免金额"
          />
        </el-form-item>
        <el-form-item
          v-if="form.data.preferenceType === 0"
          label="使用门槛"
          prop="purchaseAbove"
          :verify="{ type: 'int', gte: 0 }"
        >
          <PriceInput
            v-model="form.data.purchaseAbove"
            :disabled="form.status !== 'c'"
            placeholder="请输入使用门槛"
          />
          <form-item-tip value="0代表无使用门槛" />
        </el-form-item>
        <el-form-item label="可用时间类型" prop="validTimeType" verify>
          <KiSelect
            v-model="form.data.validTimeType"
            placeholder="请选择可用时间类型"
            :options="[
              { dataName: '时间区间', dataValue: 0 },
              { dataName: 'X天可用', dataValue: 1 }
            ]"
            :disabled="form.status !== 'c'"
          />
        </el-form-item>
        <el-form-item
          v-if="form.data.validTimeType == 0"
          label="可用时间"
          prop="useStartTime"
          verify
        >
          <TimeRangePicker
            :start.sync="form.data.useStartTime"
            :end.sync="form.data.useEndTime"
            :pickerOptions="pickerOptions"
            type="date-time"
            placeholder="请选择可用时间"
            :disabled="form.status !== 'c'"
          />
        </el-form-item>
        <el-form-item
          v-if="form.data.validTimeType == 1"
          label="可用时间"
          prop="useTimePeriod"
          :verify="{ type: 'int', gte: 1, lte: 2000 }"
        >
          <span>领券当天起</span>
          <el-input
            class="!w-150px !mx-10px"
            v-model="form.data.useTimePeriod"
            placeholder="请输入可用时间"
            :disabled="form.status !== 'c'"
          ></el-input>
          <span>天内可用</span>
          <form-item-tip
            value="有效期按自然天计算。举例：如设置领券当日起2天内可用，用户在5月20日10:00时领取优惠券，则该优惠券的可用时间为5月20日的10:00:00至5月21日的23:59:59"
          />
        </el-form-item>
        <h2 class="title">领取和使用规则</h2>
        <el-form-item label="每人限领次数" verify prop="personLimit">
          <el-radio-group v-model="form.data.personLimit">
            <el-radio
              :label="-1"
              class="w-100px"
              :disabled="form.status !== 'c'"
            >
              不限次数
            </el-radio>
            <el-radio
              :label="form.data.personLimit > 0 ? form.data.personLimit : 1"
              :disabled="form.status !== 'c'"
            >
              每个用户限领
            </el-radio>
            <el-input-number
              class="!w-150px !inline-block !ml-[-15px]"
              v-model="limit"
              :min="0"
              :precision="0"
              :disabled="form.data.personLimit == '-1' || form.status !== 'c'"
            ></el-input-number>
            <span class="text-14px pl-10px">次</span>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品详情展示" verify prop="withCode">
          <el-checkbox
            v-model="form.data.withCode"
            :true-label="1"
            :false-label="0"
            :disabled="form.status !== 'c'"
          >
            可兑券
          </el-checkbox>
          <el-checkbox
            v-model="form.data.withPage"
            :true-label="1"
            :false-label="0"
            :disabled="form.status !== 'c'"
          >
            可领券
          </el-checkbox>
        </el-form-item>
        <el-form-item label="使用说明" verify prop="useRemark">
          <el-input
            v-model="form.data.useRemark"
            cols="3"
            type="textarea"
            placeholder="请输入优惠码使用说明"
            maxlength="1000"
            show-word-limit
          ></el-input>
        </el-form-item>

        <el-form-item label="退款退券">
          <el-radio-group
            v-model="form.data.refundCoupon"
            :disabled="form.status !== 'c'"
          >
            <el-radio :label="1" :disabled="true">开启</el-radio>
            <!-- <el-radio :label="0" :disabled="father.type=='edit'">关闭</el-radio> -->
          </el-radio-group>
          <form-item-tip value=" 设置为开启，订单退款后优惠码仍然可用" />
        </el-form-item>
      </template>
    </KiFormDialog>

    <!-- 优惠码列表 -->
    <codeList ref="codeL" />
    <!-- 优惠码二维码 -->
    <QrCodePreview ref="qrCode" />
  </div>
</template>

<script>
import codeList from './components/codeList'
import BoundGoods from '@/components/BoundGoods'
import pageMixin from '@/utils/pageMixin'
import useAdmateAdapter from '@/utils/useAdmateAdapter'
import QrCodePreview from '@/components/QrCodePreview'
export default {
  components: { BoundGoods, codeList, QrCodePreview },
  mixins: [pageMixin],
  setup: () =>
    useAdmateAdapter({
      urlPrefix: 'sot-admin-api/product/couponActivity',
      axiosConfig: {
        r: {
          url: 'queryCouponActivityById'
        }
      },
      form: {
        data: {
          refundCoupon: 1,
          availableInDetail: 1,
          withCode: 0,
          withPage: 0
        }
      }
    }, {
      afterRetrieve({ data }) {
        if (data?.id) {
          this.$POST(
            'sot-admin-api/product/couponActivity/selectProductListWithActivityPage',
            {
              couponActivityId: data.id,
              pageNo: 1,
              pageSize: 10000 // 后端未提供直接查询已绑定商品接口，用分页接口代替
            }
          ).then(res => {
            if (res.errorCode === '00000') {
              this.form.data.couponActivityProductCreateDtoList = res.data.records.map(
                _ => ({ productId: _.productId })
              )
              this.$forceUpdate()
            }
          })
        }
        if (data.personLimit !== -1) {
          this.limit = data.personLimit
        }
      },
    }),
  watch: {
    limit (n, o) {
      if (o !== undefined) {
        this.form.data.personLimit = n
      }
    }
  },
  data () {
    return {
      frontStatusList: [
        { dataName: '未开始', dataValue: 0 },
        { dataName: '进行中', dataValue: 1 },
        { dataName: '已结束', dataValue: 2 },
        { dataName: '已失效', dataValue: 3 }
      ],
      pickerOptions: {
        // 时间限制
        startDisabledDate (time, start, end) {
          let date = new Date()
          let othe = new Date(time)
          if (othe.getTime() < date.getTime() - 24 * 60 * 60 * 1000) {
            return true
          }
          return false
        }
      },
      limit: undefined
    }
  },
  methods: {
    createQrCode (item) {
      this.$refs.qrCode.show({
        title: item.name + ' - 优惠码',
        text: `${import.meta.env.VITE_APP_QRCODE_URL}/promoCodeQRCode?id=${item.id}`,
        tips: '扫码领取优惠码'
      })
    },
    // 优惠码推广
    share (row) {
      this.frow = this._.cloneDeep(row)
      this.showExtension = true
    },
    // 失效
    lose (row) {
      this.$confirm(
        `设置失效后，用户无法再领取该优惠码，商家无法再编辑优惠内容，已经领取到的优惠码，在有效期内仍可使用`,
        '停止发券',
        {
          confirmButtonText: '确定',
          cancelButtonText: '关闭',
          type: 'warning'
        }
      ).then(() => {
        this.$POST('sot-admin-api/product/couponActivity/disable', {
          id: row.id
        })
          .then(res => {
            if (res.errorCode == '00000') {
              this.$swal.success('设置失效成功!')
              this.getList()
            }
          })
          .catch(err => this.$swal.warning(err.message))
      })
    },
    showDelete (row) {
      let da = row.status
      let s1 = new Date().getTime() //当前时间
      let s2 = new Date(row.useEndTime).getTime() //结束时间
      let s3 = new Date(row.useStartTime).getTime() // 开始时间

      if (row.status == 2) {
        return 3
      }

      // 领取后n天可用类型，默认活动永久
      if (row.validTimeType == 1) {
        return 1
      }

      if (da == 3) {
        //失效
        return 3
      }
      if (s2 - s1 < 0) {
        //结束
        return 2
      }
      if (s3 < s1 && s1 < s2) {
        //进行中
        return 1
      }
      if (s1 < s3) {
        //未开始
        return 0
      }
    }
  }
}
</script>
